#include <compat/str.h>
#include <compat/memory.h>

ULONG os_strlen(const char *dest) {

	ULONG count;

	count = 0;
	while (*dest != '\0') {
		count++;
		dest++;
	}
	return count;
}

char *os_strstr(const char *haystack, const char *needle)
{
	unsigned char *cp, *haystack_end;
	const unsigned char *np = 0, *needle_end;

	if (haystack == NULL || *haystack == 0 || needle == NULL || *needle == 0)
		return (NULL);

	haystack_end = (unsigned char *)haystack + os_strlen(haystack) - 1;
	needle_end = (const unsigned char *)needle + os_strlen(needle) - 1;

	for (cp = haystack_end; cp >= (unsigned char *)haystack; cp--) {
		if (np) {
			if (*cp == *np) {
				if (--np < (const unsigned char *)needle)
					return ((char *)cp);
			}
			else
				np = 0;
		}
		if (!np && *cp == *needle_end) {
			np = needle_end - 1;
			if (np < (const unsigned char *)needle)
				return ((char *)cp);
		}
	}

	return (NULL);
}


char os_raw_toupper(char in)
{
	if (in >= 'a' && in <= 'z')
		return (char)('A' + in - 'a');
	return in;
}	

long os_strcmp(const char* dest, const char* src)
{

	const char* s1 = dest;
	const char* s2 = src;
	
	while (*s1 && *s2) {

		if (*s1 != *s2) {
			break;
		}
		s1++;
		s2++;
	}
	return *s1 - *s2;
}

long os_strcasecmp(const char *dest, const char *src)
{
	const char* s1 = dest;
	const char* s2 = src;

	while (*s1 && *s2) {
		if (os_raw_toupper(*dest) != os_raw_toupper(*src))
			break;
		dest++;
		src++;
	}

	return (os_raw_toupper(*s1) == os_raw_toupper(*s2));

}
